//导入重置样式
require("../../assets/css/reset.css");
//导入公共样式
require("../../assets/css/basic.css");
//导入标准样式
require("../../assets/css/normalize.css");
//导入iconfont.css
require("../../assets/fonts/iconfont.css");
//导入样式
require("./sports_running.less");
//引入date时间模块
const date = require("../../utils/date.js");
//引入js模块
const dom = require("../../utils/dom.js");
//引入axios公共工具
const axios = require("../../utils/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	//1.点击按钮显示继续结束按钮
	dom.get("#btn").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#hidden").style.display = "flex";
		clearInterval(timer);
	});
	//2.点击继续按钮继续跑步
	dom.get("#playBox").addEventListener("click", function () {
		dom.get("#btn").style.display = "block";
		dom.get("#hidden").style.display = "none";
		start();
	});

	//3.地理定位
	AMap.plugin("AMap.Geolocation", function () {
		var geolocation = new AMap.Geolocation({
			// 是否使用高精度定位，默认：true
			enableHighAccuracy: true,
			// 设置定位超时时间，默认：无穷大
			timeout: 10000,
			// 定位按钮的停靠位置的偏移量
			offset: [10, 20],
			//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
			zoomToAccuracy: true,
			//  定位按钮的排放位置,  RB表示右下
			position: "RB",
		});

		geolocation.getCurrentPosition(function (status, result) {
			if (status == "complete") {
				console.log("定位成功", result);
			} else {
				console.log("定位失败");
			}
		});
	});
	//4.计算距离
	var p1 = [104.065751, 30.657453];
	var p2 = [104.05843, 30.53565];
	// 返回 p1 到 p2 间的地面距离，单位：米
	var dis = AMap.GeometryUtil.distance(p1, p2);
	//5. 定时器模拟跑步数据
	let duration = 0; //持续时间
	let meter = 0; //总里程
	let calorie = 0; //卡路里
	let timer = null; //定时器标识
	//设置一个函数用于启动定时器
	function start() {
		timer = setInterval(function () {
			//速度
			let speed = getRand(3, 7);
			dom.get("#nub").textContent = speed + "米/秒";
			//时间
			duration++;
			dom.get("#time").textContent = date.getHMS(duration);
			//里程
			meter += speed;
			dom.get("#mileage").textContent = (meter / 1000).toFixed(3); //保留三位小数
			//卡路里
			calorie = 60 * (meter / 1000).toFixed(3) * 1.036;
			dom.get("#carlorie").textContent = calorie.toFixed(2);
		}, 100);
	}
	start();

	//随机获取两个整数之间的随机数
	function getRand(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	//6.点击结束跳转页面并保存数据
	dom.get("#endBox").addEventListener("click", function () {
		axios
			.post("/api/exercise/save", {
				type: 0,
				duration,
				calorie,
				meter,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("跑步结束");
					location.href = "sports_run.html";
				}
			});
	});
});
